
import styled from 'styled-components';
import React, { CSSProperties, useState, useEffect, useRef } from 'react';
import { Button, Card, Table, Modal, Space, Drawer } from 'antd';
import { TableOutlined, PlusOutlined, MinusOutlined, RobotOutlined, MoreOutlined } from '@ant-design/icons';

import { confirm } from '@tauri-apps/plugin-dialog';
import { dsDeleteById, dsFind, mergeQueryCondition, metaFindClass, QueryCondition, QueryExtention, QueryOptions } from '@/services/local';

import { ObjectCrudEditor } from './object-editor';

export interface DataCrudTableProps {
    style?: CSSProperties;
    classIdentifier: string;
    conditions?: QueryCondition,
    queryExtentions?: QueryExtention,
    queryOptions?: QueryOptions,
    excludes?: Array<String>,
    create?: any,
    update?: any,
    onChange?: () => Promise<void> | void;
}

export const DataCrudTable: React.FC<DataCrudTableProps> = (props) => {

    const [loading, setLoading] = useState<boolean>(false);

    const [isModalOpen, setIsModalOpen] = useState(false);

    const [clazz, setClass] = useState<any>();

    const [assistantOpen, setAssistantOpen] = useState<boolean>(false);

    const [columns, setColumns] = useState<any>([]);

    const [data, setData] = useState<any[]>([]);

    const [selected, setSelected] = useState<any | null>(null);

    const [page, setPage] = useState<number>(1);

    const [pageSize, setPageSize] = useState<number>(10);

    const [total, setTotal] = useState<number>(0);

    useEffect(() => {
        //获取元数据
        metaFindClass(props.classIdentifier).then((clazz) => {
            console.log(clazz);
            setClass(clazz);
            if (clazz && clazz.attributes) {
                setColumns(clazz.attributes.map((attr, index) => {
                    return {
                        title: attr.title,
                        dataIndex: attr.name,
                        key: attr.name,
                        ellipsis: true,
                    };
                }).filter((attr, index) => {
                    return !(props.excludes && props.excludes.indexOf(attr.key) >= 0)
                }).concat([{
                    title: '操作',
                    dataIndex: '操作',
                    key: '操作',
                    width: '140px',
                    render: (_, record, index) => {
                        return (
                            <Space size="middle" key={record.identifier + index}>
                                <Button
                                    type={'link'}
                                    size={'small'}
                                    onClick={async () => {
                                        setSelected(record);
                                        setIsModalOpen(true);
                                    }}
                                >编辑</Button>
                                <Button
                                    type={'link'}
                                    size={'small'}
                                    onClick={async () => {
                                        const confirmed2 = await confirm('确定要删除该对象吗？', { title: '删除对象', kind: 'warning' });
                                        if (confirmed2) {
                                            let res = await dsDeleteById(0, props.classIdentifier, record.id);
                                            // await metaDataRemoveObject(record.id);
                                            props.onChange && await props.onChange();
                                            request(props.classIdentifier, page, pageSize, props.conditions, props.queryExtentions, props.queryOptions);
                                        }
                                    }}
                                >删除</Button>
                            </Space>
                        );
                    }
                },]));
            }
        })
    }, [props.classIdentifier, props.excludes]);

    const request = async (identifier: string, page: number, pageSize: number, conditions: any, extentions?: any, options?: any,) => {
        setLoading(true);
        const { total, data } = await dsFind(0, identifier, mergeQueryCondition([conditions, {
            page: page,
            page_size: pageSize
        }]));
        setData(data);
        setTotal(total);
        setLoading(false);
    };

    useEffect(() => {
        request(props.classIdentifier, page, pageSize, props.conditions, props.queryExtentions, props.queryOptions);
    }, [props.classIdentifier, props.conditions, props.queryExtentions, props.queryOptions, page, pageSize]);

    return (
        <Content style={props.style}>
            <StyledCard
                style={{
                }}
                title={'对象列表'}
                styles={{
                    body: {
                        padding: '0px 2px',
                        overflow: 'auto',
                        height: 'calc(100% - 40px)'
                    }
                }}
            >
                <Buttons>
                    <Button
                        style={{
                            width: '90px',
                            backgroundColor: '#E02020'
                        }}
                        key={'ai'}
                        onClick={async () => {
                            setAssistantOpen(true);
                        }}
                        type={'primary'}
                        icon={<RobotOutlined />}
                    >AI</Button>,
                    <Button
                        style={{
                            width: '90px'
                        }}
                        key={'add'}
                        onClick={async () => {
                            //
                            setSelected(null);
                            setIsModalOpen(true);
                        }}
                        type={'primary'}
                        icon={<PlusOutlined />}
                    >添加</Button>
                </Buttons>
                <Table
                    bordered
                    loading={loading}
                    rowKey={'identifier'}
                    pagination={{
                        showSizeChanger: true,
                        total: total,
                        current: page,
                        pageSize: pageSize,
                        onChange: (page, pageSize) => {
                            setPage(page);
                        },
                        onShowSizeChange: (current, size) => {
                            setPageSize(size);
                        }
                    }}
                    dataSource={data} columns={columns} />
            </StyledCard>
            <Modal
                styles={{
                    content: {
                        minWidth: '600px',
                        minHeight: '400px'
                    }
                }}
                title={selected ? "编辑对象" : "添加对象"}
                footer={false}
                destroyOnClose={true}
                open={isModalOpen}
                onOk={async () => {
                    //刷新
                    setIsModalOpen(false);
                }} onCancel={async () => {
                    //刷新
                    setIsModalOpen(false);
                }}>
                <ObjectCrudEditor
                    {...(selected ? props.update : props.create)}
                    clazz={clazz}
                    onFinish={async () => {
                        await request(props.classIdentifier, page, pageSize, props.conditions, props.queryExtentions, props.queryOptions);
                        setIsModalOpen(false);
                        props.onChange && await props.onChange();
                    }}></ObjectCrudEditor>
            </Modal>
            <Drawer
                title="AI助手"
                onClose={() => {
                    setAssistantOpen(false);
                }}
                width={'calc(100% - 220px)'}
                destroyOnClose={true}
                open={assistantOpen}>
            </Drawer>
        </Content >
    )
}

const Content = styled.div`
    flex:  1;
    width: 100%;
    padding: 6px 6px;
    display: flex;
    gap: 6px;
`;

const Buttons = styled.div`
    width: 100%;
    padding: 6px 6px;
    display: flex;
    justify-content: flex-end;
    gap: 6px;
`;

const StyledCard = styled(Card)`
    width: 100%;
`

const EmptyContainer = styled.div`
    height: 100%;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size:12px;
`;


export default {}